package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.TravelComment;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.query.TravelCommentQuery;
import cn.wolfcode.luowowo.repository.TravelCommentRepository;
import cn.wolfcode.luowowo.service.ITravelCommentService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {

    @Autowired
    private TravelCommentRepository repository;
    @Override
    public TravelComment get(String id) {
        Optional<TravelComment> optional = repository.findById(id);
        //如果数据库不是空的
        if (optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    @Autowired
    private MongoTemplate template;
    /**
     * 分页操作
     * @param qo 分页条件
     * @return
     */
    @Override
    public Page list(TravelCommentQuery qo) {
        Query query = new Query();
        //在评论的分页操作中  只显示该攻略的评论  过滤一下
        if (StringUtils.hasLength(qo.getTravelId())){
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        }
        Page<TravelComment> page = DBHelper.query(template, TravelComment.class, query, qo.getPageable());
        return page;
    }

    @Override
    public void commentAdd(TravelComment comment, UserInfo userInfo) {
        comment.setCreateTime(new Date());
        BeanUtils.copyProperties(userInfo,comment);
        comment.setUserId(userInfo.getId());
        comment.setId(null);
        //首先判断是否评论别人的评论
        TravelComment travelComment = this.get(comment.getRefComment().getId());
        //如果是空的话  就是普通评论
        if (travelComment == null){

        }else {//评论的评论
            comment.setType(TravelComment.TRAVLE_COMMENT_TYPE);
            comment.setRefComment(travelComment);
        }
        repository.save(comment);
    }
}
